{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c1b2b7d9",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "e9684509",
   "metadata": {},
   "source": [
    "# 语音识别测试-百度API-ASR"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "26478ff1",
   "metadata": {},
   "outputs": [],
   "source": [
    "API_KEY = 'smxkOHWjqLVljEmIry5vuSYI'\n",
    "SECRET_KEY = 'ky3FZeSSDurxLyLLqZ2kPaEnts9NH1W1'\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "6f69c7d8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# coding=utf-8\n",
    "\n",
    "import sys\n",
    "import json\n",
    "import time\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "\n",
    "    timer = time.perf_counter\n",
    "else:\n",
    "    import urllib2\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "\n",
    "    if sys.platform == \"win32\":\n",
    "        timer = time.clock\n",
    "    else:\n",
    "        # On most other platforms the best timer is time.time()\n",
    "        timer = time.time\n",
    "\n",
    "\n",
    "# 需要识别的文件\n",
    "AUDIO_FILE = 'audio/16k.wav'  # 只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "# 文件格式\n",
    "FORMAT = AUDIO_FILE[-3:];  # 文件后缀只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "\n",
    "CUID = '123456PYTHON';\n",
    "# 采样率\n",
    "RATE = 16000;  # 固定值\n",
    "\n",
    "# 普通版\n",
    "\n",
    "DEV_PID = 1537;  # 1537 表示识别普通话，使用输入法模型。根据文档填写PID，选择语言及识别模型\n",
    "ASR_URL = 'http://vop.baidu.com/server_api'\n",
    "SCOPE = 'audio_voice_assistant_get'  # 有此scope表示有asr能力，没有请在网页里勾选，非常旧的应用可能没有\n",
    "\n",
    "\n",
    "# 极速版\n",
    "\n",
    "class DemoError(Exception):\n",
    "    pass\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN start \"\"\"\n",
    "\n",
    "TOKEN_URL = 'http://aip.baidubce.com/oauth/2.0/token'\n",
    "\n",
    "\n",
    "def fetch_token(API_KEY,SECRET_KEY):\n",
    "    params = {'grant_type': 'client_credentials',\n",
    "              'client_id': API_KEY,\n",
    "              'client_secret': SECRET_KEY}\n",
    "    post_data = urlencode(params)\n",
    "    if (IS_PY3):\n",
    "        post_data = post_data.encode('utf-8')\n",
    "    req = Request(TOKEN_URL, post_data)\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "        print('token http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    if (IS_PY3):\n",
    "        result_str = result_str.decode()\n",
    "\n",
    "#     print(result_str)\n",
    "    result = json.loads(result_str)\n",
    "#     print(result)\n",
    "    if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "        if SCOPE and (not SCOPE in result['scope'].split(' ')):  # SCOPE = False 忽略检查\n",
    "            raise DemoError('scope is not correct')\n",
    "#         print('SUCCESS WITH TOKEN: %s ; EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN end \"\"\"\n",
    "\n",
    "def asr(token,AUDIO_FILE):\n",
    "    speech_data = []\n",
    "    with open(AUDIO_FILE, 'rb') as speech_file:\n",
    "        speech_data = speech_file.read()\n",
    "    length = len(speech_data)\n",
    "    if length == 0:\n",
    "        raise DemoError('file %s length read 0 bytes' % AUDIO_FILE)\n",
    "\n",
    "    params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID}\n",
    "    #测试自训练平台需要打开以下信息\n",
    "    #params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID, 'lm_id' : LM_ID}\n",
    "    params_query = urlencode(params);\n",
    "\n",
    "    headers = {\n",
    "        'Content-Type': 'audio/' + FORMAT + '; rate=' + str(RATE),\n",
    "        'Content-Length': length\n",
    "    }\n",
    "\n",
    "    url = ASR_URL + \"?\" + params_query\n",
    "#     print(\"url is\", url);\n",
    "#     print(\"header is\", headers)\n",
    "    # print post_data\n",
    "    req = Request(ASR_URL + \"?\" + params_query, speech_data, headers)\n",
    "    try:\n",
    "        begin = timer()\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "        print(\"Request time cost %f\" % (timer() - begin))\n",
    "    except  URLError as err:\n",
    "        print('asr http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "\n",
    "    if (IS_PY3):\n",
    "        result_str = str(result_str, 'utf-8')\n",
    "#     print(result_str)\n",
    "    with open(\"result.txt\", \"w\") as of:\n",
    "        of.write(result_str)\n",
    "    return result_str"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f9da2a10",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 语音识别执行如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "ddea3018",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'24.e26fda2685c4f1bd79a52fef1bd2d861.2592000.1655381761.282335-19331335'"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "xu_token = fetch_token(API_KEY,SECRET_KEY)\n",
    "xu_token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "55288d59",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Request time cost 0.393005\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'{\"corpus_no\":\"7098678082998294150\",\"err_msg\":\"success.\",\"err_no\":0,\"result\":[\"北京科技馆。\"],\"sn\":\"37852882201652789787\"}\\n'"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "asr(xu_token,'audio/16k.wav')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3357f295",
   "metadata": {},
   "source": [
    "# 语音识别自动回复文本机器人\n",
    "\n",
    "> 1. 准备录制音频文件 （完成）\n",
    "> 2. 调用语音识别，将音频转成文本 （已完成）\n",
    "> 3. 文本自动回复 （已完成）原理: 问和答，I/O 输入和输出----特点： key:value"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3066f384",
   "metadata": {},
   "source": [
    "## 准备录制音频文件"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4da27d3f",
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install SpeechRecognition"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eda81044",
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install PyAudio\n",
    "\n",
    "!pip install pipwin\n",
    "!pipwin instll PyAudio"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "862f08f4",
   "metadata": {},
   "outputs": [],
   "source": [
    "import speech_recognition\n",
    "r = speech_recognition.Recognizer()\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将数据保存到wav文件中\n",
    "with open(\"1.wav\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b3e3ceac",
   "metadata": {},
   "source": [
    "## 文本自动回复(自定义)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "8ec48c95",
   "metadata": {},
   "outputs": [],
   "source": [
    "qa = {\n",
    "    \"你好\":\"你好呀，有什么事么？\",\n",
    "    \"你叫什么名字\":\"我是人见人爱，花见花开的小小度呀\",\n",
    "    \"你多大了\":\"这是很私密的问题，我今年18岁了。\",\n",
    "    \"苹果用英文怎么说\":\"apple\",\n",
    "    \"今天天气\":\"我这边墨迹天气显示，今天广州30度，晴\"\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "631cea9b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'你好呀，有什么事么？'"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "qa.get('你好')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "c81830cf",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'我是人见人爱，花见花开的小小度呀'"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "qa.get('你叫什么名字')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "76dc96e2",
   "metadata": {},
   "source": [
    "## 实践"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "8f99d1f1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Request time cost 1.744306\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'apple'"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 1. 录制音频文件\n",
    "import speech_recognition\n",
    "r = speech_recognition.Recognizer()\n",
    "# 通过调用电脑的麦克风进行音频的获取\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将数据保存到wav文件中\n",
    "with open(\"1.wav\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))\n",
    "    \n",
    "# 2. 调用百度asr\n",
    "xu_token = fetch_token(API_KEY,SECRET_KEY)\n",
    "asr_result = eval(asr(xu_token,\"1.wav\"))['result'][0][:-1]  # eval()---> str to dict\n",
    "# asr_result\n",
    "\n",
    "# 3. 文本自动回复\n",
    "qa.get(asr_result)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "49885d53",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.13"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}